<?php

/**
 * Description of BaseAdminPresenter
 *
 * Copyright (c) 2011 Tomáš Holub (tomas.holub@webadvice.cz)
 * 
 * @author Tomáš Holub (tomas.holub@webadvice.cz)
 * @package OverFishCMS
 */

namespace OverFish\Routers;

use Nette, Nette\Application\Request, Nette\DI\Container;

class ArticleRouter implements Nette\Application\IRouter
{
    
    /** @var Nette\DI\Container */
    private $context;
    
    public function __construct(Container $container) {
        $this->context = $container;
    }
    
    function match(Nette\Http\IRequest $httpRequest){
        
        $slug = $httpRequest->getUrl()->getPathInfo();
        
        if (substr($slug, -1, 1) == "/") {
            $slug = substr($slug, 0, -1);
        }
        
        $conn = $this->context->database;
        
        // Test for menu item
        $result = $conn->select("id, type")
                            ->from("page")
                            ->where("slug = %s", $slug)->fetch();
        
        if ($result) {
            $request = new Nette\Application\Request('Page', 'GET', array(
                "action" => "article",
                "type" => $result->type,
                "slug" => $slug,
                "id" => $result->id,
            ));
            return $request;
        }
        
        
    }

    function constructUrl(Request $appRequest, Nette\Http\Url $refUrl) {
        if (isset($appRequest->params["id"])) {
            $id = $appRequest->params["id"];
        } else if (isset($appRequest->params["action"])) {
            $id = $appRequest->params["action"];
        } else {
            return Null;
        }
        
        
        $conn = $this->context->database;
        
        $result = $conn->select("slug")
                            ->from("page")
                            ->where("id = %i", $id)->fetch();
        
        if ($result) {
            $refUrl->setPath("/" . $result->slug . "/");
            
            return $refUrl->getAbsoluteUrl();
        }
        
        
        
        
    }
}

?>
